package cn.holy.app.xcddt.ui.activity.record

import androidx.lifecycle.Observer
import androidx.core.content.ContextCompat
import android.text.TextUtils
import cn.holy.app.xcddt.R
import cn.holy.app.xcddt.app.App
import cn.holy.app.xcddt.database.dao.RecordUserDao
import cn.holy.app.xcddt.domain.RecordGroup
import cn.holy.app.xcddt.domain.RecordUserBean
import cn.holy.app.xcddt.net.callback.LoadingCallback
import cn.holy.app.xcddt.repository.RecordRepository
import cn.holy.app.xcddt.repository.UserRepository
import cn.holy.app.xcddt.ui.activity.base.BaseActivity
import cn.holy.app.xcddt.utils.HDateUtils
import cn.holy.app.xcddt.utils.format
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.orhanobut.logger.Logger
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog
import kotlinx.android.synthetic.main.activity_start.*
import kotlinx.android.synthetic.main.layout_record_group_item.*
import java.util.*
import javax.inject.Inject


/**
 * Created by 69568 on 2018/2/27.
 */
@Route(path = "/app/record/start")
class StartActivity : BaseActivity(), DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
    override fun onTimeSet(view: TimePickerDialog?, hourOfDay: Int, minute: Int, second: Int) {
        et_record_time.text = "$hourOfDay:$minute"
        recordCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
        recordCalendar.set(Calendar.MINUTE, minute)
        recordCalendar.set(Calendar.SECOND, second)
    }

    override fun onDateSet(view: DatePickerDialog?, year: Int, monthOfYear: Int, dayOfMonth: Int) {
        val month = monthOfYear + 1;
        et_record_date.text = "$year-$month-$dayOfMonth"
        recordCalendar.set(Calendar.YEAR, year)
        recordCalendar.set(Calendar.MONTH, monthOfYear)
        recordCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)

    }

    @Inject
    lateinit var recordRepository: RecordRepository

    @Inject
    lateinit var userRepo: UserRepository


    lateinit var recordUserDao: RecordUserDao

    lateinit var recordCalendar: Calendar

    override fun initData() {
        val loading = getLoading("加载中")
        recordRepository.netGroup(object : LoadingCallback<Int> {
            override fun onStart() {
                loading.show()
            }

            override fun onError(msg: String) {
                hideLoading(loading)
                showTips(msg, QMUITipDialog.Builder.ICON_TYPE_INFO)
            }

            override fun onSuccess(t: Int) {
                hideLoading(loading)
                et_record_number.setText(t.toString())
            }

            override fun onSuccess() {
            }

            override fun onCompleted() {
            }

        })
        val loadUser = userRepo.loadUser()
        et_record_people.setText(loadUser?.username)

    }

    override fun initView() {
        App.appComponent.inject(this)
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        top_bar.setTitle("开始新巡查").setTextColor(ContextCompat.getColor(this, R.color.colorWhite))
        top_bar.addLeftImageButton(R.mipmap.ic_back, R.id.action_close).setOnClickListener({ finish() })

        val count = recordRepository.countGroup()
        recordUserDao = App.appDataBase.recordUserDao()
//        val record_username = recordRepository.loadRecordUserNames().joinToString(",")
        recordUserDao.loadSelectUsers().observe(this, Observer<List<RecordUserBean>> { list ->
            val listData = list?.map {
                it.username
            }
            val text = listData?.joinToString(",")
            et_record_username.setText(text)
        })

//        et_record_number.setText((count + 1).toString())
        val now = Date()
        val calendar = Calendar.getInstance()
        recordCalendar = calendar
        calendar.time = now
        et_record_date.text = now.format("yyyy-MM-dd")
        et_record_time.text = now.format("hh:mm")

        et_record_date.setOnClickListener {
            //            val dp = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
//                val month = monthOfYear + 1
//                et_record_date.text = "$year-$month-$dayOfMonth"
//            }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
//            dp.show()

            val mdp = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
            mdp.show(fragmentManager, "datePicker");
        }
        et_record_time.setOnClickListener {
            val mtp = TimePickerDialog.newInstance(this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
            mtp.show(fragmentManager, "timePicker");
        }
        btn_start_new.setOnClickListener {
            checkForm()
        }

    }


    private fun checkForm() {
        if (TextUtils.isEmpty(et_record_username.text.toString())) {
            showTips("巡查人不能为空", QMUITipDialog.Builder.ICON_TYPE_INFO)
            return
        }

        if (TextUtils.isEmpty(et_record_date.text.toString())) {
            showTips("巡查时间不能为空", QMUITipDialog.Builder.ICON_TYPE_INFO)
            return
        }
        if (TextUtils.isEmpty(et_record_people.text.toString())) {
            showTips("记录人不能为空", QMUITipDialog.Builder.ICON_TYPE_INFO)
            return
        }
        if (et_record_number.text.toString().toInt() <= 0) {
            showTips("巡查次数必须大于", QMUITipDialog.Builder.ICON_TYPE_INFO)
            return
        }
        val recordGroup = RecordGroup()
        val date = HDateUtils.strToDate(et_record_date.text.toString())
        Logger.d(date)
        recordGroup.record_date = recordCalendar.time
        recordGroup.user_id = userRepo.loadUser()!!.id
        recordGroup.record_num = et_record_number.text.toString().toInt()
        recordGroup.record_people = et_record_people.text.toString()
        recordGroup.record_username = et_record_username.text.toString()

        recordRepository.saveRecordGroup(recordGroup)

        showTips("正在新建巡查", QMUITipDialog.Builder.ICON_TYPE_LOADING, object : Callback {
            override fun onSuccess() {
                this@StartActivity.showTips("新建成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS, object : Callback {
                    override fun onSuccess() {

                        ARouter.getInstance().build("/app/record/detail").navigation()
                        finish()
                    }

                })
            }
        })

    }

    override fun initLayout() {
        setContentView(R.layout.activity_start)
    }

}